//
//  FZUserViewModel.swift
//  MyWeiBo
//
//  Created by fangzhengwei on 2017/3/29.
//  Copyright © 2017年 fangzhengwei. All rights reserved.
//

import UIKit

class FZUserViewModel: NSObject {

    var useraccount : FZUserAcoount?
    
    override init() {
        super.init()
        useraccount = FZUserAcoount.getUserAcount()
    }
    
    var islogin : Bool {
        
        if useraccount?.expires_date?.compare(Date()) == ComparisonResult.orderedDescending {
            //  如果过期时间大于当前时间,表示没有过期
            return true
        }
        return false
    }
    static let sharedUser = FZUserViewModel()
    
    func loadUserData(code : String , successClosure : @escaping (Bool)->()) {
        
        FZNetworkTools.sharedTools.loadAccessToken(code: code, finishClosure: { (reponse, error) in
            
            if error != nil{
                
                print(error!)
                successClosure(false)
                return
            }
            let userAccountDic = reponse as! [String : Any]
            
            //字典转模型
            let model = FZUserAcoount(dic: userAccountDic)
            
            //获取用户信息
            self.receiveUserData(userModel: model,successClosure: successClosure)
        })

    }
   private func receiveUserData(userModel : FZUserAcoount,successClosure : @escaping (Bool)->()) {
        
        FZNetworkTools.sharedTools.loadUserAccount(accessToken: userModel.access_token ?? "", uid: userModel.uid) { (reponse, error) in
            
            if error != nil{
                
                print(error!)
                successClosure(false)
                return
            }

            let responseDic = reponse as! [String : Any]
            
            userModel.name = responseDic["name"] as! String?
            userModel.avatar_large = responseDic["avatar_large"] as! String?
            
            userModel.saveUserAccount()
            self.useraccount = userModel
            successClosure(true)
        }
    }
    
    
    
}
